Namespace("org.wattdepot.gdata");

// Creates a simple HTML table generator.
// Create instances using 'new' so that the internal updatable state is
// supported.
org.wattdepot.gdata.HtmlTable = function() {
  // Contains a list of arrays containing
  var rows = [];
  var attributes = [];

  // Add a new row of data to the end of this table.
  // rowData should be an array of elements.
  // All rows should have the same number of elements.
  function addRow(rowData) {
    rows.push(rowData);
  }

  // Add a new attribute to the table tag.
  function addAttribute(newAttribute) {
    attributes.push(newAttribute);
  }

  // Adds a Google datatable to the htmltable.
  function addTable(datatable, formatted) {
    for ( var row = 0; row < datatable.getNumberOfRows(); row++) {
      var rowElements = [];
      for ( var column = 0; column < datatable.getNumberOfColumns(); column++) {
        var cellVal = formatted ? datatable.getFormattedValue(row, column) : datatable.getValue(row, column);
        rowElements.push(cellVal);
      }
      rows.push(rowElements);
    }
  }

  // Returns the HTML for the table based upon the data.
  function getHtml() {
    var html = '<table ';
    // Add all table attributes.
    for ( var i = 0; i < attributes.length; i++) {
      html += attributes[i] + ' ';
    }
    html += '>';
    // Now add all rows.
    for ( var i = 0; i < rows.length; i++) {
      html += '<tr>';
      var rowData = rows[i];
      for ( var j = 0; j < rowData.length; j++) {
        html += '<td>' + rowData[j] + '</td>';
      }
      html += '</tr>';
    }
    html += '</table>';
    return html;
  }

  return {
    // Public interface to this function.
    addRow : addRow,
    addAttribute : addAttribute,
    addTable : addTable,
    getHtml : getHtml
  };
};
